﻿using AntUnion.FrameWork.Model.Models;
using AntUnion.FrameWork.Util;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Util.Extension;

namespace AntUnion.FrameWork.Web.Areas.Console.Controllers
{
    [Area("Console")]
    public class MT5TransactionsController : BaseController
    {
        private readonly IWebHostEnvironment _hostingEnv;
        private readonly mtContext _context;
        public MT5TransactionsController(mtContext context, IWebHostEnvironment hostingEnv) : base(context, hostingEnv)
        {
            _context = context;
            _hostingEnv = hostingEnv;
        }
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> GetListJson(int page, int limit, long login = 0, string orderNumber = "", string fullName = "", string operationType = "", string creationTime = "")
        {
            ListResult res = new ListResult();
            try
            {
                var data = from y in _context.Mt5Transactions
                           join m in _context.Mt5Users on y.Login equals m.Login
                           join c in _context.CrmUsers on m.CrmId equals c.Id
                           select new
                           {
                               orderNumber = y.Id,
                               tradingAccount = y.Login,
                               changeAmount = y.Amount.ToString("#,##0.00"),
                               operationType = y.Type,
                               creationTime = y.CreateDate,
                               transactionOrderNumber = y.OrderId,
                               fullName = c.Name,
                               loginName = c.LoginName,
                               //remark = y.Remark,
                               receivedAmount = y.Toamount == null ? "0.00" : ((decimal)y.Toamount).ToString("#,##0.00"),
                               commission = y.Toamount == null ? "0.00" : ((decimal)y.Fees).ToString("#,##0.00"),
                               aduitUser = y.Type == "rechargeAndDeposit" ? _context.CrmDeposits.Where(k => k.Mt5Order == y.OrderId && k.State == 2).Select(k => k.Reviewer).FirstOrDefault() : y.Type == "withdrawalOfFunds" ? _context.CrmWithdrawals.Where(k => k.Mt5Order == y.OrderId && k.State == 2).Select(k => k.Reviewer).FirstOrDefault() : y.Type == "internalTransferIn" ? _context.CrmInternaltransfers.Where(k => k.Mt5Order == y.OrderId && k.State == 2).Select(k => k.Reviewer).FirstOrDefault() : (y.Type == "systemDeposit" || y.Type == "systemWithdrawal") ? y.Creator : "",
                               aduitTime = y.Type == "rechargeAndDeposit" ? _context.CrmDeposits.Where(k => k.Mt5Order == y.OrderId && k.State == 2).Select(k => k.OverDate).FirstOrDefault().ToString() : y.Type == "withdrawalOfFunds" ? _context.CrmWithdrawals.Where(k => k.Mt5Order == y.OrderId && k.State == 2).Select(k => k.OverDate).FirstOrDefault().ToString() : y.Type == "internalTransferIn" ? _context.CrmInternaltransfers.Where(k => k.Mt5Order == y.OrderId && k.State == 2).Select(k => k.OverDate).FirstOrDefault().ToString() : (y.Type == "systemDeposit" || y.Type == "systemWithdrawal") ? y.CreateDate.ToString() : "",
                               remark = y.Type == "rechargeAndDeposit" ? _context.CrmDeposits.Where(k => k.Mt5Order == y.OrderId && k.State == 2).Select(k => k.Remark).FirstOrDefault() : y.Type == "withdrawalOfFunds" ? _context.CrmWithdrawals.Where(k => k.Mt5Order == y.OrderId && k.State == 2).Select(k => k.Remark).FirstOrDefault() : y.Type == "internalTransferIn" ? _context.CrmInternaltransfers.Where(k => k.Mt5Order == y.OrderId && k.State == 2).Select(k => k.Remark).FirstOrDefault() : y.Remark,
                           };

                data = data.OrderByDescending(k => k.creationTime);

                if (login != 0)
                {
                    data = data.Where(k => k.tradingAccount == login);
                }
                if (!string.IsNullOrEmpty(orderNumber))
                {
                    data = data.Where(k => k.transactionOrderNumber.Contains(orderNumber));
                }
                if (!string.IsNullOrEmpty(fullName))
                {
                    long loginNo = 0;
                    try
                    {
                        loginNo = Convert.ToInt64(fullName);
                    }
                    catch
                    {
                        loginNo = 0;
                    }
                    if (loginNo == 0)
                    {
                        data = data.Where(k => k.fullName.Contains(fullName) || k.loginName.Contains(fullName));
                    }
                    else
                    {
                        data = data.Where(k => k.fullName.Contains(fullName) || k.loginName.Contains(fullName) || k.tradingAccount == loginNo);
                    }
                    //data = data.Where(k => k.fullName.Contains(fullName) || k.loginName.Contains(fullName));
                }
                if (!string.IsNullOrEmpty(operationType))
                {
                    data = data.Where(k => k.operationType == operationType);
                }
                if (!string.IsNullOrEmpty(creationTime) && creationTime.Contains(" - "))
                {
                    string[] registrationTimes = creationTime.Split(new string[] { " - " }, StringSplitOptions.None);
                    DateTime startTime = Convert.ToDateTime(registrationTimes[0]);
                    DateTime endTime = Convert.ToDateTime(registrationTimes[1]);
                    data = data.Where(k => k.creationTime > startTime && k.creationTime < endTime);
                }
                res.Code = 0;
                res.Count = data.Count();
                res.Data = await data.Skip((page - 1) * limit).Take(limit).ToListAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }

        /// <summary>
        /// 操作类型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetOperationTypes()
        {
            ListResult res = new ListResult();
            try
            {
                var data = _context.Mt5Transactions.OrderBy(k => k.Type).Select(k => k.Type).Distinct().ToList();
                res.Code = 0;
                res.Count = data.Count();
                res.Data = data.ToList();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
    }
}
